<template>
  <div class="app-container">
    <el-row :gutter="20" class="header">
      <el-col :span="7">
        <el-input placeholder="请输入姓名..." v-model="queryForm.query" clearable></el-input>
      </el-col>
      <el-button type="primary" :icon="Search" @click="initStuList">搜索</el-button>
      <el-button type="success" :icon="DocumentAdd" @click="handleDialogValue()">新增</el-button>

     
    <el-upload
      class="upload-demo"
      action="#"
      :auto-upload="false"
      :on-change="handleChange"
      :before-upload="beforeUpload"
    >
      <el-button type="primary">上传</el-button>
    </el-upload>
    <el-button type="success" @click="submitUpload" :disabled="!file">提交上传</el-button>
      <!-- 删除 -->
      <!-- <el-popconfirm title="您确定批量删除这些记录吗？" @confirm="handleDelete(null)">
        <template #reference>
          <el-button type="danger" :disabled="delBtnStatus" :icon="Delete">批量删除</el-button>
        </template>
      </el-popconfirm> -->
    </el-row>
    <el-table :data="tableData" @selection-change="handleSelectionChange" stripe style="width: 100%">
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column prop="avatar" label="头像" width="80" align="center">
        <template v-slot="scope">
          <img :src="getServerUrl() + 'media/userAvatar/' + scope.row.avatar" width="50" height="50" />
        </template>
      </el-table-column> -->
      <el-table-column prop="stu_name" label="姓名" width="100" align="center" />
      <!-- <el-table-column prop="stu_phone" label="联系方式" width="120" align="center" /> -->
      <el-table-column prop="stu_phone" label="联系方式" width="120" align="center" />
      <el-table-column prop="stu_id" label="身份证号" width="180" align="center" />
      <el-table-column prop="stu_type" label="(专/学硕)" width="100" align="center" />
      <el-table-column prop="stu_nation" label="民族" width="100" align="center" />
      <el-table-column prop="stu_politic_outlook" label="政治面貌" width="100" align="center" />
      <el-table-column prop="stu_graduate_school" label="本科院校" width="100" align="center" />
      <el-table-column prop="stu_graduate_major" label="本科专业" width="100" align="center" />
      <el-table-column prop="stu_grade_english" label="英语成绩" width="100" align="center" />
      <el-table-column prop="stu_grade_math" label="数学成绩" width="100" align="center" />
      <el-table-column prop="stu_grade_politics" label="政治成绩" width="100" align="center" />
      <el-table-column prop="stu_grade_procourse" label="专业课成绩" width="100" align="center" />
      <el-table-column prop="stu_grade_total" label="总分" width="100" align="center" />
      <!-- <el-table-column prop="roles" label="拥有角色" width="200" align="center">
        <template v-slot="scope">
          <el-tag size="small" type="warning" v-for="item in
  scope.row.roleList"> {{ item.name }}</el-tag>
        </template>
      </el-table-column> -->
      <!-- <el-table-column prop="status" label="状态？" width="200" align="center">
        <template v-slot="{ row }">
          <el-switch v-model="row.status" @change="statusChangeHandle(row)" active-text="正常" inactive-text="禁用"
            :active-value="1" :inactive-value="0">
          </el-switch>
        </template>
      </el-table-column> -->
      <el-table-column prop="stu_honor" label="荣誉" width="400" />
      <el-table-column prop="action" label="操作" width="200" fixed="right" align="center">
        <template v-slot="scope">
          <el-button type="primary" :icon="Tools" @click="handleRoleDialogValue(scope.row.stu_id, scope.row.roleList)">分配角色
          </el-button>
          <!-- 重置密码 -->
          <!-- <el-popconfirm v-if="scope.row.username != 'python222'" title="您确定要对这
  个用户重置密码吗？" @confirm="handleResetPassword(scope.row.stu_id)">
            <template #reference>
              <el-button type="warning" :icon="RefreshRight">重置密码</el-button>
            </template>
          </el-popconfirm> -->
          <el-button type="primary"  :icon="Edit"
            @click="handleDialogValue(scope.row.stu_id)"></el-button>
          <!-- <el-popconfirm  title="您确定要删除
  这条记录吗？" @confirm="handleDelete(scope.row.stu_id)">
            <template #reference>
              <el-button type="danger" :icon="Delete" />
            </template>
          </el-popconfirm> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:currentPage="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
      :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :stu_id="stu_id" :dialogTitle="dialogTitle"
      @initStuList="initStuList"></Dialog>
    <RoleDialog v-model="roleDialogVisible" :sysRoleList="sysRoleList" :roleDialogVisible="roleDialogVisible" :stu_id="stu_id"
      @initStuList="initStuList"></RoleDialog>
  </div>

</template>
<script setup>
import { Search, Delete, DocumentAdd, Edit, Tools, RefreshRight } from '@element-plus/icons-vue'
import requestUtil, { getServerUrl } from "@/util/request"
import { ref } from 'vue'
import Dialog from './components/stuDialog'
import RoleDialog from '../sys/user/components/roleDialog'

// 请求api
import {fileUpload} from "@/util/request"
import {getStuList,delStuList} from "@/api/stu_teacher"
// 导入excel
import XLSX from 'xlsx'
import { toast } from '@/util/util'


// 用户添加form
const dialogVisible = ref(false)
const dialogTitle = ref("")
const stu_id = ref("-1")

// 用户角色
const sysRoleList = ref([])
const roleDialogVisible = ref(false)


const tableData = ref([]);

const total = ref(0)
const queryForm = ref({
  query: '',
  pageNum: 1,
  pageSize: 10
})

// 初始化学生列表
const initStuList = async () => {
  const res = await getStuList(queryForm.value)
  tableData.value = res.data.stuList;
  total.value = res.data.total;
}
initStuList();
const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1;
  queryForm.value.pageSize = pageSize;
  initStuList()
}
const handleCurrentChange = (pageNum) => {
  queryForm.value.pageNum = pageNum;
  initStuList()
}

const handleDialogValue = (id) => {
  console.log(typeof(id),"aaaaaaaaaa")
  if (id) {
    stu_id.value = id;
    dialogTitle.value = "学生信息修改"
  } else {
    stu_id.value = '-1';
    dialogTitle.value = "学生信息添加"
  }
  dialogVisible.value = true
}

const delBtnStatus = ref(true)
const multipleSelection = ref([])
const handleSelectionChange = (selection) => {
  console.log("勾选了")
  console.log(selection)
  multipleSelection.value = selection;
  delBtnStatus.value = selection.length == 0;
}

// 多选删除 -- 这里删除使用的stu_id相当于user表中的user_name
const handleDelete = async (stu_id) => {
  var stu_ids = []
  if (stu_id) {
    stu_ids.push(stu_id)
  } else {
    multipleSelection.value.forEach(row => {
      stu_ids.push(row.stu_id)
    })
  }

  const res = await  delStuList(stu_ids)
  if (res.data.code == 200) {
    toast('执行成功!')
    initStuList();
  } else {
    toast(res.data.msg,"error")
  }
}



// const handleResetPassword = async (id) => {
//   const res = await requestUtil.get("user/resetPassword?id=" + id)
//   if (res.data.code == 200) {
//     toast('执行成功!')
//     initStuList();
//   } else {
//     toast(res.data.msg,"error")
//   }
// }

// const statusChangeHandle = async (row) => {
//   let res = await requestUtil.post("user/status", {
//     id: row.id, status:
//       row.status
//   });
//   if (res.data.code == 200) {
//     toast('执行成功!')
//   } else {
//     toast(res.data.msg,"error")
//     initStuList();
//   }
// }



// const handleRoleDialogValue = (userId, roleList) => {
//   id.value = userId;
//   sysRoleList.value = roleList;
//   roleDialogVisible.value = true
// }


// 导入学生信息
const file = ref(null);
const handleChange = (fileInfo) => {
  file.value = fileInfo.raw;
};
const beforeUpload = (uploadFile) => {
  const isExcel = uploadFile.name.endsWith('.xlsx') || uploadFile.name.endsWith('.xls');
  if (!isExcel) {
    toast("只能上传 Excel 文件!",'error')
  }
  return isExcel;
};

const submitUpload = async () => {
  if (!file.value) {
    toast("请先选择 Excel 文件!",'error')
    return;
  }

  const formData = new FormData();
  formData.append('excel_file', file.value);

  try {
    const response = await fileUpload("stu_teacher/uploadStuExcel",formData)
    console.log(response)
    toast('文件上传成功')
  } catch (error) {
    toast('文件上传失败','error')
  }
};
</script>

<style lang="scss" scoped>
.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

::v-deep th.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 13px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>